import requests
from utils.tools import session, logger
from config import conf, qanything_api_local_doc_chat, qanything_headers


class LocalDocQAClient:

    def __init__(self, question: str, kb_ids: list, bot_id: str = None):
        self.question = question
        self.url = qanything_api_local_doc_chat
        self.headers = qanything_headers
        self.kb_ids = kb_ids
        self.user_id = conf.get_value("QANYTHING_USER_ID")
        self.bot_id = bot_id

    def _prepare_request_data(self):
        """私有方法：准备请求数据"""
        if not self.bot_id:
            return {
                "user_id": self.user_id,
                "kb_ids": self.kb_ids,
                "question": self.question,
            }
        else:
            return {
                "bot_id": self.bot_id,
                "user_id": self.user_id,
                "kb_ids": self.kb_ids,
                "question": self.question,
            }

    def _send_request(self, url, headers, data):
        """私有方法：发送请求"""
        try:
            response = session.post(url, headers=headers, json=data, timeout=180)
            return response
        except requests.RequestException as e:
            logger.error(f"请求错误: {e}")
            raise Exception(f"请求错误: {e}")

    def _handle_response(self, response):
        """私有方法：处理响应"""
        try:
            response.raise_for_status()
            return response.json()
        except requests.exceptions.HTTPError as http_err:
            logger.error(f"HTTP错误: {http_err}")
            raise Exception(f"请求错误: {http_err}")
        except Exception as err:
            logger.error(f"其他错误: {err}")
            raise Exception(f"请求错误: {err}")

    def query_local_doc(self):
        """查询本地文档"""
        data = self._prepare_request_data()
        try:
            response = self._send_request(self.url, self.headers, data)
            return self._handle_response(response)
        except requests.RequestException as e:
            logger.error(f"请求失败: {e}")
            raise requests.RequestException(f"请求失败: {e}")
